<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 搜索与添加区 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="querryInfo.query"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>

      <el-table :data="userlist" :border="true" stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="姓名" prop="loginName"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobilePhone"></el-table-column>
        <el-table-column label="角色" prop="role"></el-table-column>
        <el-table-column label="状态" prop="userStats">
          <!-- 作用域插槽 -->
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.userState"
              @change="userStateChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteUser(scope.row)"
            ></el-button>
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="querryInfo.pageNum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="querryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加用户的对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        label-width="70px"
        :rules="addFormRules"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="passward">
          <el-input v-model="addForm.passward"></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="addForm.phone"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 确认删除对话框 -->
    <el-dialog title="删除用户" :visible.sync="deleteDialogVisible" width="30%">
      <span>确定要删除该用户吗？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmDeleteUser">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    var checkEmail = function (rule, vale, cb) {
      // 验证邮箱的正则表达式
      const regEmail = /^[a-zA-Z0-9_-]+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(vale)) {
        return cb()
      }
      cb(new Error('请输入合法邮箱'))
    }
    var checkMobile = function (rule, vale, cb) {
      const regPhone = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regPhone.test(vale)) {
        return cb()
      }
      cb(new Error('请输入合法手机号'))
    }

    return {
      // 获取用户列表参数
      querryInfo: {
        query: '',
        pageNum: 1,
        pageSize: 2,
      },
      userlist: [],
      total: 0,
      // 添加用户对话框
      addDialogVisible: false,
      // 删除用户对话框
      deleteDialogVisible: false,

      needDeleteUser: {},
      addForm: {
        username: '',
        passward: '',
        email: '',
        phone: '',
      },
      addFormRules: {
        username: [
          {
            required: true,
            message: '请输入用户名',
            trigger: 'blur',
          },
          {
            min: 3,
            max: 10,
            message: '用户名的长度在3-10个字符之间',
            trigger: 'blur',
          },
        ],
        passward: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur',
          },
          {
            min: 3,
            max: 6,
            message: '密码的长度至少6个字符',
            trigger: 'blur',
          },
        ],
        email: [
          {
            required: true,
            message: '请输入邮箱',
            trigger: 'blur',
          },
          { validator: checkEmail, trigger: 'blur' },
        ],
        phone: [
          {
            required: true,
            message: '请输入手机号',
            trigger: 'blur',
          },
          { validator: checkMobile, trigger: 'blur' },
        ],
      },
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const res = await this.$get('/login-register-service/user-list', {
        pmarms: this.querryInfo,
      })
      if (res.code !== 200) return this.$message.error('获取用户列表失败')
      this.userlist = res.data.wrapData
      this.total = res.data.total
      console.log(res)
    },
    // 监听pageSize 改变 事件
    handleSizeChange(newSize) {
      this.querryInfo.pageSize = newSize
      // 这里可以发起请求，根据请求页码，页面数，获得新数据
      this.getUserList()
    },
    // 监听页码 改变 事件
    handleCurrentChange(newPage) {
      console.log(newPage)
      this.querryInfo.pageSize = newPage
      this.getUserList()
    },
    // 监听switch开关状态
    userStateChange(userInfo) {
      const that = this
      this.$post(
        '/login-register-service/modify/user/state',
        {
          customerId: userInfo.customerId,
          state: userInfo.userState,
        },
        true
      ).then(
        function (suc) {
          if (suc.code !== 200) {
            userInfo.userState = !userInfo.userState
            that.$message.error('跟新用户状态失败')
          } else {
            that.$message.success('跟新用户状态成功')
          }
        },
        function (ero) {
          userInfo.userState = !userInfo.userState
          that.$message.error('跟新用户状态失败')
        }
      )
    },
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    addUser() {
      const that = this
      console.log(that.addDialogVisible)
      this.$refs.addFormRef.validate(function (value) {
        if (!value) {
          return
        }
        console.log(that.addDialogVisible)
        const res = that.$post('/login-register-service/add/user', that.addForm)
        res.then(
          function (suc) {
            if (suc.code !== 200) {
              that.$message.error(suc.msg)
            } else {
              that.$message.success(suc.msg)
              that.addDialogVisible = false
              console.log('--', that.addDialogVisible)
            }
          },
          function (ero) {
            that.$message.error('添加用户失败,请检查网络')
          }
        )
      })
    },
    deleteUser(value) {
      this.needDeleteUser = value
      this.deleteDialogVisible = true
    },
    confirmDeleteUser() {
      const that = this
      const res = this.$post(
        '/login-register-service/delete/user',
        {
          customerId: this.needDeleteUser.customerId,
        },
        true
      )
      res.then(
        function (suc) {
          if (suc.code !== 200) {
            that.$message.error(suc.msg)
          } else {
            that.$message.success(suc.msg)
            that.deleteDialogVisible = false
            that.userlist.pop()
          }
        },
        function (fail) {
          that.$message.error('添加用户失败,请检查网络')
        }
      )
    },
  },
}
</script>

<style lang='less' scoped>
</style>
